package com.sc.byahi.user.client;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.sc.byahi.user.shared.Profile;

@Deprecated
public class EmailSender extends Composite {
	private final FlexTable ft = new FlexTable();
	private Button sendEmail = new Button("Send");
	private Button cancel = new Button("Cancel");
	private TextArea body = new TextArea();

	public EmailSender(final Profile p) {
		initWidget(ft);
		int row = 0;
		ft.setHTML(row, 0, "To: ");
		ft.setHTML(row++, 1, p.getId().toString());

		ft.setHTML(row, 0, "Message: ");
		ft.setWidget(row++, 1, body);

		FlowPanel fp = new FlowPanel();
		fp.add(sendEmail);
		fp.add(cancel);
		ft.setWidget(row++, 1, fp);

		sendEmail.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				if (validate().isEmpty()) {
					String message = body.getText().trim();
					if (message.length() > 300) {
						message = message.substring(0, 299);
					}

					GreetingService.Util.getInstance().sendMessage(AppController.get().getCurrentProfileId(), p.getId(), message, new AsyncCallback<Boolean>() {
						@Override
						public void onSuccess(Boolean result) {
							PopupPanel popup = (PopupPanel) (ft.getParent().getParent());
							popup.hide();
						}

						@Override
						public void onFailure(Throwable caught) {
							UIUtil.showDialog(Arrays.asList("Some error occured in sending email. Please try again.", "If the error persists, please contact administrator."), "Email sending failed.");
						}
					});
				}

			}
		});

		cancel.addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				PopupPanel popup = (PopupPanel) (((Button) event.getSource()).getParent().getParent());
				popup.hide();
			}
		});

	}

	private List<String> validate() {
		body.removeStyleName("invalidEntry");

		List<String> errors = new ArrayList<String>();

		String bodyText = body.getText().trim();
		if ("".equals(bodyText)) {
			body.addStyleName("invalidEntry");
			errors.add("Message text is empty.");
		}

		if (!errors.isEmpty()) {
			UIUtil.showDialog(errors, "Please complete following fields");
		}

		return errors;
	}

}
